#!/usr/bin/python

import sys
try:
  import pygame.mixer
  audio = True
except ImportError:
  audio = False
import pygame
from pygame.locals import *

from Core.CGraphics import Graphics
from Core.CImage import Image
from Core.CScene import Scene
from Scenes.CMenuScene import MenuScene

import pickle
import copy

currentScene = [None]

def main():
  # Initialise pygame audio, pygame main, screen and window.
  if audio:
    pygame.mixer.pre_init(44100, -16, 2, 1024) #-16 means signed 16 bits.
  pygame.init()

  if not audio or pygame.mixer.get_init() is None:
    print "Couldn't initialise audio."
    #return 1

  screen = pygame.display.set_mode((1024, 768))
  pygame.display.set_caption('The Book of Sands')

  g = Graphics(screen)
  currentScene[0] = MenuScene(g.getScreenSize(), audio)

  time = pygame.time.get_ticks()

  # Event loop
  while 1:
    for event in pygame.event.get():
      if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
        return
      elif event.type == MOUSEBUTTONDOWN:
        if event.button == 1: #left
          button = 0
        elif event.button == 3: #right
          button = 1

        s = currentScene[0].mouseInput(button, event.pos)
        if s is not None:
          print 'switching to', s
          currentScene.insert(0, s)
          

    #updating
    newtime = pygame.time.get_ticks()
    currentScene[0].update(newtime-time)
    time = newtime

    #drawing
    currentScene[0].draw(g)
    pygame.display.flip()

    pygame.time.wait(10)

if __name__ == '__main__':
  main()
